import axios from "axios";
import type { ResultData } from "./interface";
import { ElLoading } from "element-plus";
import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosError,
  AxiosResponse,
  InternalAxiosRequestConfig
} from "axios";

export default class RequestHttp {
  instance: AxiosInstance;
  loading?: any;
  public constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    /**
     * @description 请求拦截器
     */
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        this.loading = ElLoading.service({
          text: "正在请求数据....",
          background: "rgba(0, 0, 0, 0.5)"
        });
        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );
    /**
     * @description 响应拦截器
     */
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        // 将loading移除
        this.loading?.close();
        const data = response.data;
        return data;
      },
      (error: AxiosError) => {
        this.loading?.close();
        return Promise.reject(error);
      }
    );
  }
  /**
   * @description 常用请求方法封装
   */
  get<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.instance.get(url, { params });
  }
  post<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.instance.post(url, params);
  }
}
